import {toast} from "sonner";
import {useEffect, useRef, useState} from "react";
import {Html5Qrcode} from "html5-qrcode";
import {ArrowLeft} from "lucide-react";
import {useNavigate} from "react-router-dom";
import {useMutation} from "@tanstack/react-query";
import userService from "@/api/services/userService.ts";
import {useUserToken} from "@/store/userStore.ts";

export const QRScannerPage = () => {
    const navigate = useNavigate()
    const [isScanning, setIsScanning] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const html5QrCodeRef = useRef<Html5Qrcode | null>(null);
    const scannerInitialized = useRef(false);

    const userToken = useUserToken();
    const [isLoading, setIsLoading] = useState(false);
    const checkQRCodeMutation = useMutation({
        mutationFn: userService.checkQRCode,
    });


    // 启动扫描器的函数
    const startScanner = async () => {
        if (!html5QrCodeRef.current) return;

        try {
            const qrCodeSuccessCallback = async (decodedText: string) => {
                // 暂停扫描器
                await stopScanner();

                // 请求校验二维码
                await handleCheckQRCode(decodedText);
            };

            const qrCodeErrorCallback = (errorMessage: string) => {
                // 处理扫描错误
                console.debug("扫描错误:", errorMessage);
            };

            // 扫描器配置
            const config = {
                fps: 10,
                qrbox: {width: 250, height: 250},
                rememberLastUsedCamera: true,
                aspectRatio: 1.0,
            };

            setIsScanning(true);
            setError(null);

            // 启动扫描器
            await html5QrCodeRef.current.start(
                {facingMode: "environment"}, // 优先使用后置摄像头
                config,
                qrCodeSuccessCallback,
                qrCodeErrorCallback
            );

        } catch (err) {
            console.error(`无法启动扫描器:`, err);
            const errorMessage = err instanceof Error ? err.message : "未知错误";
            setError(errorMessage);

            if (errorMessage.includes("Permission denied") || errorMessage.includes("NotAllowedError")) {
                toast.error("摄像头权限被拒绝，请在浏览器设置中允许摄像头访问", {
                    position: "top-center",
                    duration: 5000,
                });
            } else if (errorMessage.includes("NotFoundError") || errorMessage.includes("未检测到")) {
                toast.error("未检测到可用的摄像头设备", {
                    position: "top-center",
                    duration: 5000,
                });
            } else if (errorMessage.includes("NotSupportedError")) {
                toast.error("当前浏览器不支持摄像头访问，请使用HTTPS协议或更换浏览器", {
                    position: "top-center",
                    duration: 5000,
                });
            } else {
                toast.error(`无法启动扫描器：${errorMessage}`, {
                    position: "top-center",
                    duration: 5000,
                });
            }
            setIsScanning(false);
        }
    };

    // 暂停扫描器的函数
    const stopScanner = async () => {
        if (html5QrCodeRef.current) {
            try {
                html5QrCodeRef.current.pause();
                setIsScanning(false);
            } catch (err) {
                console.error("暂停扫描器时出错:", err);
            }
        }
    };

    // 恢复扫描器的函数
    const resumeScanner = async () => {
        if (html5QrCodeRef.current) {
            try {
                html5QrCodeRef.current.resume();
                setIsScanning(true);
                setError(null);
            } catch (err) {
                console.error("恢复扫描器时出错:", err);
                // 如果恢复失败，尝试重新启动
                await startScanner();
            }
        }
    };


    // 校验二维码
    const handleCheckQRCode = async (data: any) => {
        setIsLoading(true);
        try {
            await checkQRCodeMutation.mutateAsync({
                qrcode_info: data,
                token: userToken.token,
                lng: '',
                lat: '',
            })
            toast.success("验证成功", {
                position: "top-center",
            });

        } catch (err) {
            toast.error("验证失败:" + err.message, {
                position: "top-center",
            });
        } finally {
            setIsLoading(false);
            await resumeScanner();
        }
    }


    useEffect(() => {
        const scannerId = "reader";

        // 防止重复初始化
        if (scannerInitialized.current) return;
        scannerInitialized.current = true;

        const initScanner = async () => {
            try {
                // 检查是否支持摄像头
                const cameras = await Html5Qrcode.getCameras();
                if (cameras.length === 0) {
                    toast.error("未检测到可用的摄像头", {
                        position: "top-center",
                    });
                    return;
                }

                html5QrCodeRef.current = new Html5Qrcode(scannerId);

                // 启动扫描器
                await startScanner();

            } catch (err) {
                console.error(`初始化扫描器失败:`, err);
                setError("初始化扫描器失败");
            }
        };

        // 延迟初始化，确保DOM已渲染
        const timer = setTimeout(() => {
            initScanner();
        }, 100);

        // 组件卸载时清理
        return () => {
            clearTimeout(timer);
            scannerInitialized.current = false;
            if (html5QrCodeRef.current) {
                html5QrCodeRef.current.stop().catch(err => {
                    console.error("清理扫描器时出错:", err);
                });
            }
        };
    }, []);

    return (
        <div className="absolute inset-0 bg-white flex flex-col items-center justify-center text-white">

            {/* 加载遮罩层 */}
            {isLoading && (
                <div
                    className="absolute inset-0 bg-black bg-opacity-70 flex flex-col items-center justify-center z-[100]">
                    <div className="w-16 h-16 border-4 border-dashed rounded-full animate-spin border-white"></div>
                    <p className="text-white mt-4">正在验证...</p>
                </div>
            )}

            {/* 左上角返回按钮 */}
            <button
                onClick={() => navigate(-1)}
                className="absolute top-4 left-4 z-50 p-1.5 rounded-full bg-white bg-opacity-20 text-black"
            >
                <ArrowLeft className="w-4 h-4"/>
            </button>

            {/* 扫描器容器 */}
            <div id="reader" className="w-full h-full"></div>

            {/* 错误状态显示 */}
            {error && (
                <div className="absolute w-full flex items-center justify-center bg-white bg-opacity-75">
                    <div className="text-center text-white p-6">
                        <div className="text-red-400 text-lg mb-4">⚠️ 扫描器启动失败</div>
                        <div className="text-xs text-gray-300">
                            <p>请确保：</p>
                            <p>• 使用HTTPS协议或localhost</p>
                            <p>• 允许浏览器访问摄像头</p>
                            <p>• 设备有可用的摄像头</p>
                        </div>
                    </div>
                </div>
            )}

            {/* 扫描成功时的遮罩层和动画 */}
            {isScanning && !error && (
                <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                    <div className="relative">
                        {/* 扫描框 */}
                        <div className="w-[250px] h-[250px] relative">
                            {/* 扫描线动画 */}
                            <div className="absolute top-0 left-0 right-0 h-1 bg-green-500 scan-line"></div>
                        </div>
                    </div>
                </div>
            )}

            {/* 提示文字 */}
            <div
                className="absolute bottom-20 left-1/2 transform -translate-x-1/2 text-white text-center pointer-events-none">
                {isScanning && !error ? (
                    <p>请将二维码对准扫描框</p>
                ) : error ? (
                    <p>扫描器暂不可用</p>
                ) : (
                    <p>正在启动扫描器...</p>
                )}
            </div>


            {/* 内联样式 */}
            <style>{`
                #reader video {
                    width: 100% !important;
                    height: 100% !important;
                    object-fit: cover;
                }
                
                #reader canvas {
                    display: none !important;
                }
                
                .scan-line {
                    animation: scanAnimation 2s linear infinite;
                }
                
                @keyframes scanAnimation {
                    0% { 
                        transform: translateY(0);
                        opacity: 1;
                    }
                    50% {
                        opacity: 1;
                    }
                    100% { 
                        transform: translateY(250px);
                        opacity: 0;
                    }
                }
                
                /* 隐藏html5-qrcode默认的UI元素 */
                #reader__dashboard_section {
                    display: none !important;
                }
                
                #reader__header_message {
                    display: none !important;
                }
                
                #reader__scan_region {
                    border: none !important;
                }
            `}</style>
        </div>
    );
};